<template>
  <div id="baseLatout">
    <Header></Header>
    <div class="main">
      <div class="container" ref="homeContainer">
        <div class="artical-wrap" ref="articalList">
          <router-view></router-view>
        </div>
        <div class="nav-wrap" :class="{ ceiling }" :style="{ left: `${ceilingLeft}px` }" ref="navBar">
          <Nav></Nav>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from '@/components/Header.vue'
import Nav from '@/components/Nav/home-nav.vue'

export default {
  name: 'DefaultLayout',
  components: {
    Header,
    Nav
  },
  data() {
    return {
      ceiling: false, // nav框是否吸顶
      ceilingLeft: 0 // nav框的宽度
    }
  },

  created() {
    this.getType()
  },

  mounted() {
    this.ceilingScroll()
    this.articalListLeftSize()
    window.addEventListener('scroll', this.ceilingScroll)
    window.addEventListener('resize', this.articalListLeftSize)
  },

  destroyed() {
    window.removeEventListener('scroll', this.ceilingScroll)
    window.removeEventListener('resize', this.articalListLeftSize)
  },

  methods: {
    // 滚动是否吸顶
    ceilingScroll() {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      let offsetTop = this.$refs.homeContainer.offsetTop

      if (scrollTop > offsetTop) {
        this.articalListLeftSize()
        this.ceiling = true
      } else {
        this.ceiling = false
      }
    },

    // 获取吸顶距离左边多少位置
    articalListLeftSize() {
      let offsetLeft = this.$refs.homeContainer.offsetLeft
      let width = this.$refs.articalList.offsetWidth
      this.ceilingLeft = offsetLeft + width + 15
    },

    getType() {
      this.$api.getType().then((res) => {
        if (res.code === 1) {
          this.$store.commit('setTypeList', res.data)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.main {
  .container {
    position: relative;
    width: 1000px;
    display: flex;
    justify-content: space-between;
    margin: 20px auto;

    .artical-wrap {
      background: #fff;
      min-height: 500px;
      width: 700px;
      margin-right: 15px;
      border: 1px solid #eee;
      margin-bottom: 40px;
    }

    .nav-wrap {
      flex: 1;

      &.ceiling {
        position: fixed;
        top: 0;
        width: 283px;
      }
    }
  }
}
</style>